#!/bin/bash

echo "开始构建版本..."

api_key='d8b167ff594eaa7efe4dee07161deed5'
file_path='build/app/outputs/apk/release/app-release.apk'
upload_url='https://www.pgyer.com/apiv2/app/upload'
lane_name='beta_pgyer'
build_type='all'

if [ -n "$1" ]; then
  build_type=$1
fi

if [ -n "$2" ]; then
  lane_name=$2
fi

if !(command -v flutter > /dev/null 2>&1); then
  echo "flutter 命令不存在"
  echo "无法完成 flutter 构建"
  exit 1
fi

if !(command -v git > /dev/null 2>&1); then
  echo "git 命令不存在"
else
  echo "拉取仓库最新代码..."
  git pull
  echo "拉取仓库最新代码完成"
fi

echo "开始清除 flutter 构建缓存文件..."
flutter clean
echo "清除 flutter 构建缓存文件完成"

if [ $build_type == 'all' -o $build_type == 'android' ]; then
  echo "开始构建 Android 版本..."
  flutter build apk

  if [ $? -eq 0 ]; then
    echo "构建 Android 版本完成"

    echo "开始上传 Android 版本到 pgyer..."
    curl -F "file=@${file_path}" -F "_api_key=${api_key}" "${upload_url}"
    echo "上传 Android 版本到 pgyer 完成"
  else 
    echo "构建 Android 版本失败"
  fi
fi

if [ $build_type == 'all' -o $build_type == 'ios' ]; then
  echo "开始构建 iOS 版本..."
  flutter build ios

  if [ $? -eq 0 ]; then
    echo "构建 iOS 版本完成"

    if !(command -v fastlane > /dev/null 2>&1); then
      echo "fastlane 命令不存在"
      echo "打包上传 iOS 版本失败"
    else
      echo "开始打包上传 iOS 版本到 pgyer..."
      cd ios/
      fastlane "${lane_name}"
      cd ..
      echo "上传 iOS 版本到 pgyer完成"
    fi

  else
    echo "构建 iOS 版本失败"
  fi

  echo "清理 iOS 构建缓存..."
  if [ -d "ios/output" ]; then
    rm -rf ios/output/
  fi
  echo "清理 iOS 构建缓存完成"
fi

echo "开始清除 flutter 构建缓存文件..."
flutter clean
echo "清除 flutter 构建缓存文件完成"

echo "构建版本完成"
